﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Ivony.Html;
using System.Drawing;
using System.Security.Cryptography;
using System.Data.Entity;
using System.Data.Entity.Core;
using System.IO;

namespace ArticleImageDownloader
{
    public class Article
    {
        public int ID { get; set; }
        /// <summary>
        /// 标题
        /// </summary>
        public string Title { get; set; }

        /// <summary>
        /// 内容
        /// </summary>
        public string Content { get; set; }
        /// <summary>
        /// 片段数
        /// </summary>
        public int Fragments { get; set; }
        /// <summary>
        /// 分类
        /// </summary>
        public int CatagoryID { get; set; }
        /// <summary>
        /// 添加时间
        /// </summary>
        public DateTime CreateTime { get; set; }

        /// <summary>
        /// 用于采编锁定，自己可重入
        /// </summary>
        public Guid? EditingBy { get; set; }

        /// <summary>
        /// 采编状态
        /// </summary>
        public ArticleState State { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public int? SimHash { get; set; }

        /// <summary>
        /// 来源
        /// </summary>
        public string SourceUrl { get; set; }

        /// <summary>
        /// 下载并上传到七牛的图
        /// </summary>
        public string Images { get; set; }
    }

    public enum ArticleState
    {
        待采编,
        已采编
    }
    public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext(string nameOrConnectionString)
               : base(nameOrConnectionString)
        {

        }
        public ApplicationDbContext()
            : base("DefaultConnection2")
        {

        }

        public DbSet<Article> Articles { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            while (true)
            {
                using (var db = new ApplicationDbContext("DefaultConnection2"))
                {
                    db.Configuration.AutoDetectChangesEnabled = false;
                    db.Configuration.LazyLoadingEnabled = false;
                    db.Configuration.ProxyCreationEnabled = false;
                    var list = db.Articles.Where(x => x.Images == null).Take(10);
                    foreach (var item in list)
                    {
                        var imageFiles = new List<string>();
                        var parser = new Ivony.Html.Parser.JumonyParser();
                        var html = parser.Parse(item.Content, null);
                        var elems = html.AllElements().ToList();
                        var images = elems.Where(x => x.Name.ToLower() == "img");
                        foreach (var image in images)
                        {
                            var src = image.Attribute("src").Value();
                            if (string.IsNullOrEmpty(src) || src.Contains("meb.com"))
                            {
                                continue;
                            }

                            Console.WriteLine(src);
                            using (var md5 = MD5.Create())
                            {
                                var bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(src));
                                var md5Hex = string.Join("", bytes.Select(x => x.ToString("X2")));
                                var fileName = md5Hex + ".jpg";
                                var filePath = "E:\\ArticleImages\\" + fileName;
                                if (!File.Exists(filePath))
                                {
                                    SocketHttpLib.HttpHelper helper = new SocketHttpLib.HttpHelper();
                                    var img = helper.HttpGetData(src);
                                    if (helper.StatusCode == 200)
                                    {
                                        if (img.All(x => x == 0))
                                        {
                                            System.IO.File.WriteAllBytes(filePath, img);
                                        }
                                    }
                                }
                                imageFiles.Add(fileName);
                                item.Content = item.Content.Replace(src, "//xzimg.meb.com/" + fileName);
                            }
                        }
                        if (imageFiles.Any())
                        {
                            item.Images = string.Join(",", imageFiles);
                        }
                        else
                        {
                            item.Images = "";
                        }
                        db.Entry(item).State = System.Data.Entity.EntityState.Modified;
                    }
                    try
                    {
                        db.SaveChanges();
                    }
                    catch (InvalidOperationException ex)
                    {
                        Console.WriteLine(ex.Message);
                        Console.ReadLine();
                        break;
                    }
                    catch (EntityException ex)
                    {
                        Console.WriteLine(ex.Message);
                        Console.ReadLine();
                        break;
                    }
                }
            }
        }
    }
}
